package com.example.crud.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crud.common.BaseResponse;
import com.example.crud.common.ErrorCode;
import com.example.crud.common.ResponseUtils;
import com.example.crud.domain.Product;
import com.example.crud.domain.request.ProductAddRequest;
import com.example.crud.domain.request.ProductDeleteRequest;
import com.example.crud.exception.BusinessException;
import com.example.crud.service.ProductService;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;

@RestController
@RequestMapping("/product")
public class ProductController {
    
    @Resource
    private ProductService productService;

    /**
     * 新增
     * @param productAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> add(@RequestBody ProductAddRequest productAddRequest){
        if (productAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String productName = productAddRequest.getProductName();
        Double price = productAddRequest.getPrice();
        long result = productService.addProduct(productName, price);
        return ResponseUtils.success(result);
    }
    
    @PostMapping("/delete")
    public BaseResponse<Boolean> delete(@RequestBody ProductDeleteRequest productDeleteRequest){
        //参数校验
        if (productDeleteRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //是否存在
        Long id = productDeleteRequest.getId();
        if (id < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //删除
        boolean b = productService.removeById(id);
        return ResponseUtils.success(b);
    }
    
    @GetMapping("/select")
    public BaseResponse<Product> select(String productName){
        Product product = productService.select(productName);
        return ResponseUtils.success(product);
    }
    
    @GetMapping("/selectPage")
    public BaseResponse<Page<Product>> selectPage(int page,int size){
        Page<Product> productPage = productService.selectPage(page,size);
        return ResponseUtils.success(productPage);
    }
    
}
